import type { VxeTableGridOptions } from '@vben/plugins/vxe-table';

import type { VbenFormSchema } from '#/adapter/form';
import type { OnActionClickFn } from '#/adapter/vxe-table';
import type { StandardPartsModel } from '#/api/equipment/models';
import type { LineModel } from '#/api/master/models';

import { message } from 'ant-design-vue';

import { getAllLineListApi, getLineListApi } from '#/api/master/line';

const _mapping: Record<number, number> = {};

/** 获取表格查询表单的字段配置。 */
export function useSearchSchema(): VbenFormSchema[] {
  return [
    {
      component: 'ApiSelect',
      componentProps: {
        allowClear: true,
        labelField: 'lineName',
        valueField: 'id',
        api: getLineListApi,
        immediate: false,
      },
      fieldName: 'lineId',
      label: '生产线',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
      },
      fieldName: 'partNo',
      label: '标件条码',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
      },
      fieldName: 'partName',
      label: '标件名称',
    },
  ];
}

/**
 * 获取编辑表单的字段配置。
 */
export function useSchema(): VbenFormSchema[] {
  return [
    {
      component: 'Input',
      fieldName: 'standardPartNo',
      label: '标准件编号',
      rules: 'required',
    },
    {
      component: 'Input',
      fieldName: 'standardPartName',
      label: '标准件名称',
      rules: 'required',
    },
    {
      component: 'ApiTreeSelect',
      componentProps: {
        allowClear: true,
        multiple: true,
        afterFetch: (data: LineModel[]) => {
          data.forEach((line) => {
            line.workstations?.forEach((workstation) => {
              _mapping[workstation.id] = line.id;
            });
          });
          return data.map((line) => ({
            value: line.id,
            label: line.lineName,
            selectable: false,
            children: line.workstations?.map((workstation) => ({
              value: workstation.id,
              label: workstation.wsCode,
              isLeaf: true,
            })),
          }));
        },
        api: getAllLineListApi,
        // TreeSelect change 事件
        onChange: (value: number[]) => {
          const distinctArray = [...new Set(value.map((id) => _mapping[id]))];
          if (distinctArray.length > 1) {
            message.warning('只能选择同一产线的点检工位');
          }
        },
      },
      dependencies: {
        trigger(values) {
          if (values.workstationIds?.length) {
            values.lineId = _mapping[values.workstationIds[0]]; // 设置产线 Id
          }
        },
        triggerFields: ['workstationIds'],
      },
      fieldName: 'workstationIds',
      label: '点检工位',
      rules: 'required',
    },
    {
      component: 'Input',
      fieldName: 'alias',
      label: '设备别名',
      help: '用于在自动点检等场合定位到具体的信号点，不需要时不用设置',
    },
    {
      component: 'Switch',
      componentProps: {
        checkedValue: 1,
        unCheckedValue: 0,
        checkedChildren: '启用',
        unCheckedChildren: '停用',
        class: 'w-auto',
      },
      fieldName: 'status',
      label: '状态',
      defaultValue: 1,
      rules: 'required',
    },
    {
      component: 'Textarea',
      componentProps: {
        showCount: true,
        maxlength: 128,
      },
      fieldName: 'remark',
      label: '备注',
    },
  ];
}

/**
 * 获取表格列配置。
 * @param onActionClick 表格操作按钮点击事件
 */
export function useColumns(
  onActionClick?: OnActionClickFn<StandardPartsModel>,
): VxeTableGridOptions<StandardPartsModel>['columns'] {
  return [
    { type: 'seq', width: 60 },
    { field: 'standardPartNo', title: '标准件编号', width: 160 },
    { field: 'standardPartName', title: '标准件名称', width: 160 },
    { field: 'line.lineName', title: '点检产线', width: 140 },
    { field: 'workstationCodes', title: '点检工位', width: 180 },
    {
      field: 'status',
      title: '状态',
      width: 100,
      cellRender: { name: 'CellTag', attrs: { useStatus: true } },
    },
    { field: 'remark', title: '备注', minWidth: 100 },
    { field: 'createdTime', title: '创建时间', width: 150 },
    {
      cellRender: {
        attrs: {
          nameField: 'standardPartName',
          nameTitle: '标件',
          onClick: onActionClick,
        },
        name: 'CellOperation',
        options: [
          'edit', // 默认的编辑按钮
          'delete', // 默认的删除按钮
        ],
      },
      field: 'operation',
      fixed: 'right',
      title: '操作',
      width: 120,
    },
  ];
}
